package com.example.server.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationSupport;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

import com.example.server.command.AbstractCommand;
import com.example.server.command.CommandFactory;

public class ApiServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3081052585186255541L;

	private final static Logger log = Log.getLogger(ApiServlet.class);

	@Override
	public void init() throws ServletException {
		super.init();
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		log.debug("init(config) start ...");
		super.init(config);

		log.debug("init(config) end ...");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		log.info("method:" + method);

		Continuation continuation = ContinuationSupport.getContinuation(req);
		continuation.setTimeout(0);
		continuation.suspend(resp);

		AbstractCommand abstractCommand = CommandFactory.getInstance().createCommand(method);
		abstractCommand.setContinuation(continuation);
		abstractCommand.run();

	}

}
